from flask import Blueprint, request
from flask_restful import Resource, Api
from model.tag import Tag
from libs.response import generate_response
from model import db
from libs.auth import login
from libs.handler import default_error_handler

tag_bp = Blueprint("tagapi", __name__, url_prefix="/v1")
api = Api(tag_bp)


class TagView(Resource):
    # 测试成功
    def post(self):
        name = request.json.get("name")
        tag_info = Tag(
            name=name
        )
        db.session.add(tag_info)
        db.session.commit()
        return generate_response(message="add tag success")

    # 测试成功
    def delete(self, id):
        result = Tag.query.get(id)
        if result is not None:
            db.session.delete(result)
            db.session.commit()
            return generate_response(message="delete tag success")
        else:
            return generate_response(status_code=10001, message="tag doesn't exist")

    # 测试成功
    def get(self, id=None):
        result_list = []
        if id is not None:
            tag = Tag.query.get(id)
            if tag is not None:
                tag.CreateAt = str(tag.CreateAt)
                result_list.append(tag)
                print(result_list)
                return generate_response(message="get tag success", data=[dict(i) for i in result_list])
            else:
                return generate_response(status_code=10001, message="tag doesn't exist")
        else:
            tags = Tag.query.all()
            for c in tags:
                c.CreateAt = str(c.CreateAt)
            result_list += tags
        return generate_response(message="get tags success", data=[dict(item) for item in result_list])


api.add_resource(TagView, '/tag')
api.add_resource(TagView, '/tag/<int:id>', endpoint="tagviewapi")